﻿
namespace Oddo.Concept.Crm.Common.Presentation.Services
{
    using System.Text.RegularExpressions;
    using DevExpress.Xpf.Bars;
    using Microsoft.Practices.Unity;
    using Oddo.Concept.Crm.Common.Presentation.Infrastructure;
    using Oddo.Concept.Crm.Common.Presentation.Interfaces;

    public interface IMenuService
    {
        void AddMainMenuItem(MenuItem item);
    }

    public class MenuService : IMenuService
    {
        private readonly BarManager _manager;
        
        public MenuService(IShellView shell)
        {
            this._manager = shell.BarManager;
        }
        public void AddMainMenuItem(MenuItem item)
        {
            var parent = GetParent(item.Parent);
            var button = new BarButtonItem
                {
                    Content = item.Title, 
                    Command = item.Command, 
                    CommandParameter = item.CommandParameter,
                    Name = "bbi" + Regex.Replace(item.Title, "[^a-zA-Z0-9]", ""),
                    Glyph = item.Image,
                    BarItemDisplayMode = item.Image == null ? BarItemDisplayMode.Content : BarItemDisplayMode.ContentAndGlyph,
                };

            if (item.BeginGroup)
            {
                var separator = new BarItemSeparator();
                _manager.Items.Add(separator);
                _manager.Items.Add(button);
                parent.ItemLinks.Add(separator);
                parent.ItemLinks.Add(button);
            }
            else
            {
                _manager.Items.Add(button);
                parent.ItemLinks.Add(button); //new BarButtonItemLink { BarItemName = button.Name });    
            }
        }

        BarSubItem GetParent(string parentName)
        {
            foreach (BarItem item in _manager.Items)
            {
                var button = item as BarSubItem;
                if (button != null && button.Content.ToString() == parentName)
                    return button;
            }
            var newParent = new BarSubItem { Content = parentName, Name = "bsi" + Regex.Replace(parentName, "[^a-zA-Z0-9]", "") };
            _manager.Items.Add(newParent);
            _manager.MainMenu.ItemLinks.Add(new BarSubItemLink { BarItemName = newParent.Name });
            return newParent;
        }
    }
}